<template>
  <div>
    <div class="filter-container">

      <el-select class="filter-item" v-model="listQuery.user_id" clearable filterable remote reserve-keyword placeholder="登录名/姓名/手机号" @change="changeMethod" :remote-method="remoteMethod" :loading="loading">
        <el-option v-for="item in selectData" :key="item.id" :label='item.name + "/" + item.username + "/" + item.phoneNumber' :value="item.id">
        </el-option>
      </el-select>

      <el-button class="filter-item" rigth style="margin-rigth: 10px;" @click="handleCreate" type="primary" icon="el-icon-plus">{{$t('preDeposit.table.add')}}</el-button>
    </div>
    <el-table border highlight-current-row height="350" :data="list" style="width: 100%;" show-summary>

      <el-table-column label="姓名" fixed="left" show-overflow-tooltip>
        <template slot-scope="scope">
          {{scope.row.user.name}}
        </template>
      </el-table-column>
      <el-table-column label="金额" min-width="120" align="center" prop="operationMoney">
        <template slot-scope="scope">
          {{scope.row.operationMoney | currency}}
        </template>
      </el-table-column>
      <el-table-column label="类型" min-width="120" align="center">
        <template slot-scope="scope">
          {{scope.row.operationType | typefilter}}
        </template>

      </el-table-column>
      <el-table-column label="创建时间" min-width="180" align="center">
        <template slot-scope="scope">
          {{scope.row.createdAt | moment('YYYY-MM-DD hh:mm:ss')}}
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <!-- <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"> -->
      <el-pagination background small @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-size="listQuery.limit" layout="prev, pager, next" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :before-close="handleClose">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="100px" style='width: 50%; margin-left:50px;'>
        <el-form-item label="选择用户" prop="user">
          <el-select v-model="temp.user" clearable filterable remote reserve-keyword placeholder="登录名/姓名/手机号" :remote-method="remoteMethodAdd" :loading="loading">
            <el-option v-for="item in selectDataAdd" :key="item.id" :label='item.name + "/" + item.username + "/" + item.phoneNumber' :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作类型" prop="operationType">
          <el-select v-model="temp.operationType" clearable placeholder="请选择类型">
            <el-option key='1' value="1" label="预存款"></el-option>
            <el-option key='2' value="2" label="积分"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="operationMoney">
          <el-input-number v-model="temp.operationMoney" :step="0.01"></el-input-number>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">{{$t('table.confirm')}}</el-button>
        <el-button v-else type="primary" @click="updateData">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>

    <!-- <el-dialog :title="预存款管理" :visible.sync="preDialogFormVisible" :before-close="handleClose">
    </el-dialog> -->
  </div>
</template>

<script>
import { scanUser } from '@/api/user'
import { getPreDepositList, getPreDepositForUser, createPreDepositForUser } from '@/api/preDeposit'

export default {
  data() {
    return {
      selectData: [],
      selectDataAdd: [],
      // user_id: '',
      loading: false,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        user_id: null
      },
      temp: {
        id: undefined,
        user: 1,
        operationMoney: 0,
        operationType: 1
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        user: [{ required: true, message: '用户必须选择', trigger: 'change' }],
        operationMoney: [{ required: true, message: '金额必须输入', trigger: 'change' }],
        operationType: [{ required: true, message: '类型必须选择', trigger: 'change' }]
      },
      preDialogFormVisible: false
    }
  },
  filters: {
    typefilter(type) {
      const typeMap = {
        1: '预存款',
        0: '赠送',
        2: '积分'
      }
      return typeMap[type]
    },
    statusFilter(status) {
      const statusMap = {
        success: 'success',
        pending: 'danger'
      }
      return statusMap[status]
    },
    currency(num, fString = '￥', cNum = 2) {
      return fString + Number(num).toFixed(cNum)
    },
    sexFilter(sex) {
      const sexMap = {
        1: '女',
        2: '男',
        0: '保密'
      }
      return sexMap[sex]
    },
    discountFilter(discount) {
      return discount * 10 + ' 折'
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      if (this.listQuery.user_id) {
        getPreDepositForUser(this.listQuery.page, this.listQuery.limit, this.listQuery.user_id).then(response => {
          var data = response.data
          this.list = data.results
          this.total = data.count
        })
      } else {
        getPreDepositList(this.listQuery.page, this.listQuery.limit).then(response => {
          var data = response.data
          this.list = data.results
          this.total = data.count
        })
      }
    },
    handleFilter() {
      this.fetchData()
    },

    handleCreatePre(row) {
      this.preDialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchData()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        user: undefined,
        operationMoney: 0,
        operationType: undefined
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => { })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createPreDepositForUser(this.temp).then(response => {
            const data = response.data
            if (data.flag) this.list.unshift(this.temp)
            this.dialogFormVisible = !data.flag
            this.$notify({
              title: '预存款/积分操作',
              message: data.flag ? '追加成功' : data.errorMsg,
              type: data.flag ? 'success' : 'error',
              duration: 5000
            })
            this.fetchData()
          })
        }
      })
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        scanUser(query).then(response => {
          this.selectData = response.data.results
          this.loading = false
        })
      } else {
        this.selectData = []
        this.loading = false
      }
    },
    remoteMethodAdd(query) {
      if (query !== '') {
        this.loading = true
        scanUser(query).then(response => {
          this.selectDataAdd = response.data.results
          this.loading = false
        })
      } else {
        this.selectData = []
        this.loading = false
      }
    },
    changeMethod(value) {
      this.listQuery.page = 1
      this.fetchData()
    }
  }
}
</script>
